<template>
  <basic-container>
    <div class="container-body">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-row>
          <el-form-item label="年度:">
            <el-date-picker v-model="query.year" type="year" placeholder="选择年" value-format="yyyy">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="考评人:">
            <el-input size="medium" v-model="query.ownUserName" placeholder="考评人"></el-input>
          </el-form-item>
          <el-form-item label="状态:">
            <el-select size="medium" v-model="query.status" placeholder="请选择" clearable>
              <el-option label="待统计" value="1"></el-option>
              <el-option label="已考评" value="2"></el-option>
              <el-option label="已结束" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button type="primary" size="medium" icon="el-icon-search" @click="onSearch" :loading="loading">搜索
            </el-button>
            <el-button size="medium" icon="el-icon-delete" @click="searchReset" :loading="loading">清空</el-button>
            <el-button type="warning" size="medium" plain icon="el-icon-download" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-row>
        <el-row>
          <el-popover
            placement="right"
            width="270"
            trigger="click">
            <el-row>
              <el-form-item label="考评年度:">
                <el-date-picker v-model="examineYear" type="year" placeholder="选择考评年度" value-format="yyyy">
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <el-button type="success" size="medium" plain icon="el-icon-document-checked" @click="handleFinishScore(examineYear)">开始统计</el-button>
            </el-row>
            <el-button slot="reference" type="success" size="medium" plain icon="el-icon-document-checked">统计考评评分</el-button>
          </el-popover>
        </el-row>
      </el-form>
      <el-table header-row-class-name="container-table-header"
                :data="data" size="medium"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id"
                v-loading="loading">
        <el-table-column prop="examineYear" label="年度" width="80">
        </el-table-column>
        <el-table-column prop="ownUserName" label="姓名">
        </el-table-column>
        <el-table-column prop="ownDeptName" label="单位">
        </el-table-column>
        <!--        <el-table-column prop="examineName" label="考评内容" min-width="100">
                </el-table-column>-->
        <el-table-column prop="score" label="考评得分" width="80">
          <template slot-scope="scope">
            <div>{{ scope.row.score > 0 ? scope.row.score : '--'}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <div>{{ scope.row.status | scoreStatus }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作" width="170">
          <template slot-scope="scope">
            <el-button type="text" size="medium" icon="el-icon-view" @click="showViewBox(scope.row)">查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="container-page">
        <el-pagination background
                       @size-change="sizeChange"
                       @current-change="currentChange"
                       :current-page="page.current"
                       :page-sizes="[10, 20, 30, 40, 50, 100]"
                       :page-size="10"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="page.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog :visible.sync="viewBox" :close-on-click-modal="!viewBox" fullscreen
               :append-to-body="true" :before-close="resetForm" width="1000px" top="5vh">
      <div slot="title">
        <span style="font-size: 20px;margin-right: 20px;">查看</span>
        <el-button @click="resetForm" size="small" type="success" plain>返回</el-button>
      </div>
      <el-form ref="optForm" :model="form" label-width="120px">
        <el-row :gutter="24">
          <el-col :span = "6">
            <div><span>年度考评：</span><span>{{form.examineName}}</span></div>
          </el-col>
          <el-col :span = "6">
            <div><span>考评项目：</span><span>{{form.projectName}}</span></div>
          </el-col>
          <el-col :span = "6">
            <div><span>考评对象：</span><span>{{form.ownUserName}}</span></div>
          </el-col>
          <el-col :span = "6">
            <div><span>所属单位：</span><span>{{form.ownDeptName}}</span></div>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="height: 40px;line-height: 40px;">
          <el-col :span="16" style="text-align: left;font-weight: bold;">
            <div>考评指标</div>
          </el-col>
          <el-col :span="2" style="text-align: center;font-weight: bold;">
            <div>分值</div>
          </el-col>
          <el-col :span="6" style="text-align: left;font-weight: bold;">
            <div>考评得分<b style="padding-left: 15px;font-size: 16px; color: red;">{{form.status > 0 ? totalScore.toFixed(1) : '--'}}</b></div>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex" v-for="option in form.options" :key="option.optionId" class="mark-content-bottom-border" style="padding-top: 20px;border-bottom: 1px solid #ebebeb;align-items: center;">
          <el-col :span="16" style="text-align: left;">
            <div>{{option.optionName}}</div>
          </el-col>
          <el-col :span="2" style="text-align: center;">
            <div>{{option.optionMaxValue}}</div>
          </el-col>
          <el-col :span="6" style="text-align: left;">
            <div>{{option.score >= 0 ? option.score : '--'}}</div>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm" size="medium" icon="el-icon-close">取消</el-button>
      </span>
    </el-dialog>

  </basic-container>
</template>

<script>
import {getDetail, getList, remove} from "@/api/kpi/score";
import {mapGetters} from "vuex";
import {finishScore} from "@/api/kpi/examine";
import {statScorePersonTotal} from "@/api/kpi/scorePerson";

export default {
  data() {
    return {
      isAdministrator: false,
      importBox: false,
      isEdit: false,
      isView: false,
      viewBox: false,
      formBox: false,
      formTitle: '',
      loading: true,
      query: {},
      form: {},
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      data: [],
      showUploadButton: true,
      fileList: [],
      channels: [],
      editorOption: {
        placeholder: "",
      },
      totalScore: 0,
      examineYear: '',
    }
  },
  computed: {
    ...mapGetters(["userInfo", "permissions"])
  },
  watch: {
  },
  created() {
    this.onLoad(this.page);
  },
  methods: {
    handleFinishScore(row) {
      if (!row){
        this.$message({
          type: "warning",
          message: "请先选择考评年度!"
        });
        return false;
      }
      this.checkIfAllScored(row).then((canProceed) => {
        if (!canProceed) return;

        this.$confirm("开始统计"+ row +"考评评分?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then((canProceed) => {
          if (!canProceed) return;
          return finishScore().then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }).catch((error) => {
            this.loading = false;
            throw error;
          });
        })
      })
    },

    checkIfAllScored(examineYear) {
      return statScorePersonTotal({ year: examineYear }).then((res) => {
        if (res.data.data.total === 0){
          this.$message({
            type: "warning",
            message: "没有找到任何考评项，无法进行考评评分统计！"
          });
          return false;
        }
        if (res.data.data.activeTotal !== 0) {
          this.$message({
            type: "warning",
            message: "还有未评分的考评项，不能进行考评评分统计!"
          });
          return false;
        }
        return true;
      })
    },
    scoreHandle() {
      this.totalScore = 0
      this.form.options.forEach(element => {
        if (element.score && Number(element.score) >= 0) {
          this.totalScore += Number(element.score)
        }
      });
    },
    showAddView() {
      this.formTitle = '新增';
      this.formBox = true;
    },
    showEditBox(row) {
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.formTitle = '编辑';
        this.formBox = true;
        this.isEdit = true;
        this.fileList = [];
        this.fileList.push({url:res.data.data.thumbUrl});
        this.scoreHandle();
      });
    },
    showViewBox(row) {
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.workId = row.id;
        this.viewBox = true;
        this.fileList = [];
        this.fileList.push({url:res.data.data.thumbUrl});
        this.scoreHandle();
      });
    },
    handleGenerate(row) {
      this.$confirm("确定一键生成考评评估?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return generate(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return remove(row.id);
      })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    resetForm() {
      this.formBox = false;
      this.isEdit = false;
      this.isView = false;
      this.form = {};
      this.formTitle = '';
      this.$refs['optForm'] && this.$refs['optForm'].resetFields();
      this.viewBox = false;
      this.fileList = [];
      this.auditBox = false;
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.current = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page, this.query);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.current, page.size, Object.assign(params, this.query)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      }, error => {
        this.loading = false;
      });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.showUploadButton = true
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
      if (this.fileList.length >= 1) {
        this.showUploadButton = false
      }
    },
    handlePreview(file) {
      window.open(file.url ? file.url : file.response.data.url)
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    handleExport() {
    },
  }
};
</script>

<style scoped  lang="scss">
::v-deep .ownDeptObject {
  .el-col {
    margin: 0!important;
    padding: 0!important;
  }
  .el-form-item {
    margin: 0!important;
  }
  .el-collapse-item__content {
    margin: 0!important;
  }
  .avue-form__menu {
    display: none;
  }
  .el-form-item__content {
    line-height: 40px;
  }
}
</style>
